

new function () {
    const ColorUtils = Packages.androidx.core.graphics.ColorUtils;
    const AnimationFloat = require('../anim/animation_foat');
    const ViewPrototype = require('../modules/view_prototype');
    const FloatMenu = require('../index');
    const {
        dp2px,
        defineValue,
        createShape
    } = require('../modules/utils');

    const mView = Symbol('view');
    const icons = Symbol('icons');
    const tints = Symbol('tints');
    const colors = Symbol('colors');
    const render = Symbol('render');
    const checked = Symbol('checked');
    const animator = Symbol('animator');
    const clickAction = Symbol('clickAction');

    /**
     * 自定义控件 ItemView
     * @param {string} name 控件名称
     * @param {FloatMenu} fm
     * @returns ImageView;
     */
    function ItemView(name, fm) {
        this.__float_menu__ = fm;
        this.name = name;
        //创建ItemView;
        this[mView] = createItemView(this);
        //call父类
        ViewPrototype.call(this, this[mView]);
        //重定向 NativeView prototype
        this[mView].__proto__ = this;
        //创建ItemView点击动画
        this[animator] = createItemClickAnimtor(this[mView]);
        this[clickAction] = null;
        this.scaleView = true;

        //监听数据发生变化
        this.defineValue('style', ItemView.STYLE_ITEM_BUTTON, style => {
            switch (style) {
                case ItemView.STYLE_ITEM_BUTTON:
                    this[checked] = null;
                    break;
                case ItemView.STYLE_ITEM_CHECKBOX:
                    this[checked] = false;
                    break;
            }
        });
        this.defineValue(checked, null, val => {
            onItemClick(this[mView], true);
        });
        this.defineValue(colors, null, val => {
            this.color = getValue(this, colors);
        });
        this.defineValue(tints, null, val => {
            this.tint = getValue(this, tints);
        });
        this.defineValue(icons, null, val => {
            this.icon = getValue(this, icons);
        });
        this.defineValue('color', null, val => {
            if ('string' === typeof val) {
                val = $colors.parseColor(val);
            }
            this[mView].getBackground().setColor(val);
        });
        this.defineValue('tint', null, val => {
            if ('number' === typeof val)
                val = $colors.toString(val);
            this.attr('tint', val);
        });
        this.defineValue('icon', null, val => {
            this.attr('src', val);
        });

        return this[mView];
    }

    //按钮样式
    ItemView.STYLE_ITEM_BUTTON = 0;
    //复选框样式
    ItemView.STYLE_ITEM_CHECKBOX = 1;

    ItemView[render] = (
        <img
            foreground='?attr/selectableItemBackground'
            clickable='true'
            gravity='center'
            elevation='2dp'
            translationZ="2dp"
            padding='8dp'
            margin='3dp' />
    );

    ItemView.prototype = {

        /**
         * @callback ItemViewOnClickCallback
         * @param {ItemView} view
         * @returns {boolean=} 是否关闭菜单 没有返回值或者返回true保持菜单开启,返回false关闭菜单
         */
        /**
         * 控件点击事件
         * @param {ItemViewOnClickCallback} callback  
         * @returns {ItemView}
         */
        onClick(callback) {
            if ('function' === typeof callback) {
                this[clickAction] = callback;
            };
            return this[mView];
        },

        /**
         * 设置图标组
         * 
         *      view.setIcons('icon_autojs_logo',...'https://..../logo.png');
         * @param {string} uri 
         * @returns {ItemView}
         */
        setIcons(uri) {
            this[icons] = Array.prototype.slice.call(arguments);
            return this[mView];
        },

        /**
         * 设置背景颜色组
         * 
         *      view.setColors('#ff0000',...'#0000ff');
         * @param {string} colorstr 字符串颜色 
         * @returns {ItemView}
         */
        setColors(colorstr) {
            this[colors] = Array.prototype.slice.call(arguments);
            return this[mView];
        },

        /**
         * 设置图标颜色组
         * 
         *      view.setTints('#ff0000',...'#0000ff');
         * @param {string} colorstr 字符串颜色 
         * @returns {ItemView}
         */
        setTints(colorstr) {
            this[tints] = Array.prototype.slice.call(arguments);
            return this[mView];
        },

        /**
         * 设置控件样式
         * 
         *      view.setStyle(FloatMenu.STYLE_ITEM_CHECKBOX)
         * 
         * @param {number} style  
         * @returns {ItemView}
         */
        setStyle(style) {
            this.style = style;
            return this[mView];
        },

        /**
         * 设置控件大小
         * @param {number} dp  
         * @returns {ItemView}
         */
        setSize(dp) {
            this.attr('w', dp);
            this.attr('h', dp);
            return this[mView];
        },

        /**
         * 设置背景圆角
         * @param {number} dp 弧度 单位:dp 
         * @returns {ItemView}
         */
        setRadius(dp) {
            this[mView].getBackground().setCornerRadius(dp2px(dp));
            return this[mView];
        },

        /**
         * 设置内边距
         * @param {number} dp 弧度 单位:dp 
         * @returns {ItemView}
         */
        setPaddings(dp) {
            let px = dp2px(dp);
            this[mView].setPadding(px, px, px, px);
            return this[mView];
        },

        /**
         * 设置边框描边
         * @param {number} width 画笔宽度 单位:px
         * @param {string} color 画笔颜色 字符串颜色
         * @param {number=} dashWidth 虚线线宽 单位:px
         * @param {number=} dashGap 虚线隔宽 单位:px 
         * @returns {ItemView}
         */
        setStroke(width, color, dashWidth, dashGap) {
            this[mView].getBackground().setStroke(width || 0, $colors.parseColor(color || '#000000'), dashWidth || 0, dashGap || 0);
            return this[mView];
        },

        /**
         * 在执行点击动画时是否缩放控件 
         * @returns {ItemView}
         */
        setAnimatorScaleView(scale) {
            this.scaleView = scale;
            return this[mView];
        },

        /**
         * 获取当前控件样式
         * @returns {number}
         */
        getStyle() {
            return this.style;
        },

        get checked() {
            return this[checked];
        },

        /**
         * 获取当前是否选中
         * @returns {boolean|null}
         */
        getChecked() {
            return this.checked;
        },

        /**
         * 设置当前是否选中
         * 只有在控件为CheckBox(复选框)样式下才能生效
         * @param {boolean} value  
         * @returns {ItemView}
         */
        setChecked(value) {
            if (this.checked !== null) {
                this[checked] = value;
            }
            return this[mView];
        },

        defineValue,
    }

    ItemView.prototype = Object.assign(ItemView.prototype, ViewPrototype.prototype);
    ItemView.prototype.constructor = ItemView;

    /**
     * @param {ItemView} view;
     * @argument View.OnClickListener
     */
    function onItemClick(view, isChecked) {
		if(view.__float_menu__.resetAutoHideFloatMenuTimer){
		   view.__float_menu__.resetAutoHideFloatMenuTimer();
		}
        let result = true;
        if (view.checked !== null && !isChecked) {
            return view.setChecked(!view.checked);
        }
        if (view[clickAction]) {
            result = view[clickAction](view, view.checked);
        } else {
            let listeners = view.__float_menu__.emitter.listeners('item_click');
            if (listeners.length) {
                result = listeners.reduce((res, listener) => {
                    result = listener(view, view.checked);
                    if (res === false)
                        return res;
                    else
                        return result;
                }, result);
            }
        }
        if (result === false)
            view.__float_menu__.setState(1);
        view[animator].start();
    }

    /**
     * 创建View
     * @returns {View} 
     */
    function createItemView(view) {
        let widget = new $ui.Widget();
        widget.onViewCreated = onViewCreated.bind(view);
        let ctx = runtime.ui.layoutInflater.newInflateContext();
        ctx.put('root', widget);
        ctx.put('widget', widget);
        return $ui.__inflate__(ctx, ItemView[render]);
    }

    /**
     * View创建事件
     * @param {ItemView} view 
     */
    function onViewCreated(view) {
        //设置layout_params
        let size = dp2px(this.__float_menu__.config.all_item_size);
        view.setLayoutParams(new android.widget.FrameLayout.LayoutParams(size, size));
        //设置 背景图
        let gd = createShape(-1, null, null);
        view.setBackground(gd);
        //启动控件裁剪
        view.setClipToOutline(true);
        //post创建点击事件
        view.post(() => {
            view.setOnClickListener({
                onClick() {
                    onItemClick(view);
                }
            });
        });
    }

    /**
     * 创建ItemView点击动画
     * @param {ItemView} view;
     */
    function createItemClickAnimtor(view) {
        let animator = new AnimationFloat(view.__float_menu__);
        animator.setDuration(view.__float_menu__.config.animator_duration_item);
        let iicons, itints, icolors;
        let f, isUpdateIcon;
        animator.onAnimatoinUpdate(animator => {
            f = animator.getAnimatedValue();
            if (view.checked !== null) {
                if (icolors)//更新背景色
                    view.color = ColorUtils.blendARGB(icolors[0], icolors[1], f);
                if (itints)//更新图标颜色
                    view.tint = ColorUtils.blendARGB(itints[0], itints[1], f);
                if (iicons && !isUpdateIcon && f > .5)//更新图标
                    (isUpdateIcon = true, view.icon = iicons);
            }
            //缩放控件
            if (view.scaleView && view.__float_menu__.isMenuOpen()) {
                scale = 1 - Math.abs(Math.abs(.5 - f) - .5) * (1 - view.__float_menu__.config.all_item_scale);
                view.setScaleX(scale);
                view.setScaleY(scale);
            }
            view.emit('animation_update', view, f);
        })
        animator.onAnimationStart(() => {
            view.setClickable(false);
            isUpdateIcon = false;
            icolors = getColors(view, colors);
            itints = getColors(view, tints);
            iicons = getIcon(view, icons);
        });
        animator.onAnimationEnd(() => {
            view.setClickable(true);
        });

        return animator;
    }

    function getValue(view, type) {
        if (Array.isArray(view[type])) {
            return view[type][view.checked ? view[type].length - 1 : 0];
        } else {
            return null;
        }
    }

    function getColors(view, key) {
        if (!Array.isArray(view[key]) || view[key].length <= 1) return null;
        let [a, b] = view[key];
        a = $colors.parseColor(a);
        b = $colors.parseColor(b || a);
        if (!view.checked) [a, b] = [b, a];
        return [a, b];
    }

    function getIcon(view, key) {
        if (!Array.isArray(view[key]) || view[key].length <= 1) return null;
        return view[key][view.checked ? 1 : 0];
    }

    module.exports = ItemView;
}